<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of giftbag
 *
 * @author Samuel
 */
defined('BASEPATH') or die('forbidden');

class Treasureboxratio_Controller extends Controller {

	private $objectTypeList;	//物品列表 
	private $boxTypeList;		//宝箱类型
	private $numberTypeList;	//数量类型
	private $materialTypeList;	//物品类型
	private $playerLevelList;	//玩家等级
	private $professionList;	//职业类型
	private $isForeverList;		//是否永久
	
	private $dyn_db;	//动态数据库连接
	private $areaList;	//区名信息
	
	private $totalRatio;	//每一样概率集合
	
	function _init() {
		check_level(50, segment(0), segment(1), segment(2, 'index'));
		set_time_limit(0);	//因加载 表比较慢，在此需要设置时间为无限长
		//require_once(CONFIGPATH . 'inc.php');
		
		$this->professionList = $this->config['inc']['type_proffessionid'];
		$this->isForeverList = $this->config['inc']['isdelete'];
		$this->areaList = get_area_list_url();
		
		//print_r($this->professionList);
		//print_r($this->isForeverList);
		
		$this->initEnum();
		
		//得到选择的区号
		$areanum = $_SESSION['area_selected_id'];
        if ($areanum == '') 
        {
            echo "<script>alert('" . translate('C_SELECT_AREA_TEXT') . "');</script>";
            return;
        }
        // db数据库
		$this->dyn_db = getTmpDbConnect(PLATFORM_ALL, 'all', $areanum, DBTYPE_DYNAMIC);
		
		$this->getTotalRatio();
	}

	function index() {
		$this->view->display("mall/treasureboxratio/index");
	}

	function flexigrid() {
		list($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page) = $this->common->get_flexigrid_params();
		

		
		$sql = "SELECT COUNT(*) AS num FROM dynamic_treasurebox_ratio  where {$where} ";
		//$sql = "SELECT COUNT(*) AS num FROM $row[logname].accountlogin  where {$where} ";
		//echo " sql:$sql ";
		
		$row = $this->dyn_db->one($sql);
		$total = $row['num'];
		$orderby = $sortname ? "ORDER BY {$sortname} {$sortorder} " : "";
			
		$sql = "SELECT {$colsinfo} FROM dynamic_treasurebox_ratio where {$where}  {$orderby} LIMIT {$offset},{$rp}";
		//$sql = "SELECT {$colsinfo} FROM $row[logname].accountlogin  where {$where}  {$orderby} LIMIT {$offset},{$rp}";
		//echo "sql2 = $sql";
		$this->dyn_db->query($sql);
		//$id = 0;
		while ($n = $this->dyn_db->get_array('default'))
		{
			//print_r($n);
			$t = $this->totalRatio[$n['box_id']][$n['choice_type']][$n['level_type']];//参考概率
			
			$t = sprintf("%.2f",(($n['ration']/$t)*100));
			
			$n['object_id']=$this->objectTypeList[$n['material_type']][$n['object_id']]['name'].' - ('.$n['object_id'].")";
			$n['box_id']=$this->boxTypeList[$n['box_id']].' - ('.$n['box_id'].")";
			$n['choice_type']=$this->numberTypeList[$n['choice_type']].' - ('.$n['choice_type'].")";
			$n['material_type']=$this->materialTypeList[$n['material_type']].' - ('.$n['material_type'].")";
			$n['profession']=$this->professionList[$n['profession']].' - ('.$n['profession'].")";
			$n['level_type']=$this->playerLevelList[$n['level_type']].' - ('.$n['level_type'].")";
			$n['starttime'] = date('Y-m-d H:i:s', $n['starttime']);
			$n['endtime'] = date('Y-m-d H:i:s', $n['endtime']);		
			$n['isforever']=$this->isForeverList[$n['isforever']].' - ('.$n['isforever'].")";
			$n['ration'] = "".$t."% - (".$n['ration'].")";
			
			$rows[] = array('id' => $n['id'], 'cell' => $n);
			//$id = $id+1;
		}
		//var_dump($rows);
		$result = array(
	            'page' => $page,
	            'total' => $total,
	            'rows' => $rows
		);

		echo json_encode($result);
	}

	function add() {
		set_time_limit(30);
		
		if (is_submit()) {
			$areaIds = $_POST['areaIds'];	//得到所有的区号
			$rowdata = $_POST['row'];	//得到表单的数据
			
			//print_r($areaIds);
			//print_r($rowdata);
			
			$rowdata['starttime'] = strtotime($rowdata['starttime']);
			$rowdata['endtime'] = strtotime($rowdata['endtime']);
			$rowdata['number'] = 1;	//物品数量是1
			$rowdata['isforever'] = 0;	//不是永久
			
			//开始时间比结束时间大，没必要再继续下去了
			if($rowdata['endtime'] < $rowdata['starttime'] )
			{
				echo "invalid endtime, endtime should be bigger than starttime ";
				return;
			}
			if( 0 >= $rowdata['ration'])
			{
				echo " ratio need big than 0";
				return;
			}
			
			//先在表中查下是否有此选项
			$sql = "select * from dynamic_treasurebox_ratio where box_id = $rowdata[box_id] and choice_type = $rowdata[choice_type] 
					and profession = $rowdata[profession] and material_type = $rowdata[material_type] and object_id = $rowdata[object_id]" ;
			//echo " sql:$sql ";

			$row = $this->dyn_db->one($sql);
			if(0 < count($row))
			{
				echo " it is have same data in database ,plz select another object ";
				return;
			}
			
			$result = $this->dyn_db->insert('dynamic_treasurebox_ratio', $rowdata);
			
			if(false == $result)
			{
				echo " insert error ";
				return ;
			}
			$indexid=$this->dyn_db->insert_id();
			
			$areanum = $_SESSION['area_selected_id'];
			//echo " areanum:$areanum ";
	
			//万不得已了，总不能传一个空数据让数据库报销了。。
			if($areanum == '')
			{
				echo "<script>alert('" . translate('C_SELECT_AREA_TEXT') . "');</script>";
				return;
			}
			
			$url = $this->areaList[$areanum]."action=51&messageid=100004&indexid=$indexid";
			//echo " url = $url ";
			$strResultStr = vpost($url);
			if ($strResultStr != '0' || $strResultStr === FALSE) {
					echo " fail ";
					$sql = "delete from dynamic_treasurebox_ratio where id = $indexid ";
					$this->db->execute($sql);
			}else
			{
					echo 'success';
			}
			
		}else 
		{

			$areas = get_area_list_host();
			array_unshift($areas, translate('ALL_AREA'));
	        set_area_list_view("arealist");
	        
			$this->view->assign('boxtype',$this->boxTypeList);	//宝箱类型
			$this->view->assign('numbertype',$this->numberTypeList);	//抽取类型
			$this->view->assign('professiontype',$this->professionList);	//职业类型
			$this->view->assign('playerlevel',$this->playerLevelList);	//等级范围
			$this->view->assign('materialtype',$this->materialTypeList);	//材料类型
			$this->view->assign('objecttype',$this->objectTypeList);	//物品类型
			
			$this->view->display("mall/treasureboxratio/add");
		}
	}

	function del($id = 0) {
		
		$areanum = $_SESSION['area_selected_id'];
		//echo " areanum:$areanum ";

		//万不得已了，总不能传一个空数据让数据库报销了。。
		if($areanum == '')
		{
			echo "<script>alert('" . translate('C_SELECT_AREA_TEXT') . "');</script>";
			return;
		}
		
		$c = 0;
		$r = '';
		if ($id === 0)
		{
			json_output($c, translate('C_INVALID_PARAM_ID'));
		}
/*
		$sql = "SELECT * FROM dynamic_treasurebox_ratio WHERE id={$id}";
		$rowdata = $this->dyn_db->one($sql);

		if(0 == count($rowdata))
		{
			echo "<script>alert('" . translate('C_SELECT_AREA_TEXT') . "');</script>";
			return;
		}
		
		//不是永久的，直接删除
		if(0 == $one['isforever'])
		{
			$sql = "delete from dynamic_treasurebox_ratio where id = $id";
			$this->dyn_db->execute($sql);
		}else 
		{
			//是永久的，暂时保留下来
			$this->dyn_db->update('dynamic_treasurebox_ratio', array('ration'=>0), array('id'=>$id));
		}
*/		
		$result = $this->dyn_db->update('dynamic_treasurebox_ratio', array('ration'=>0), array('id'=>$id));
		
		if(false != $result)
		{
			$url = $this->areaList[$areanum]."action=51&messageid=100004&indexid=$id";
			//echo " url = $url ";
			$strResultStr = vpost($url);
			if ($strResultStr != '0' || $strResultStr === FALSE) {
					echo " fail ";
					$r = translate('C_TIPS_ERROR_TEXT');
					$r = 'fail';
					$c = 1;
			}else
			{
					echo 'success';
					$r = translate('ACTIVITY_GIFTBAG_DEL');
					$r = 'success';
					$c = 0;
			}
		}

		json_output($c, $r);
		
	}

	function edit($id = 0) {
		//echo " id = $id ";
			
		//var_dump($_REQUEST);
		$rowdata = array ();
		if (is_submit()) //编辑修改
		{
			//接收收到的数据
			$rowdata = $_POST['row'];
			//var_dump($rowdata);

			$data['isforever'] = $rowdata['isforever'];
			$data['starttime'] = strtotime($rowdata['starttime']);
			$data['endtime'] = strtotime($rowdata['endtime']);
			$data['ration'] = $rowdata['ration'];
			$id = $rowdata['id'];
			
			//数据有效性检查
			$sql = "SELECT * FROM dynamic_treasurebox_ratio WHERE id={$id}";
			$rowdata = $this->dyn_db->one($sql);
	
			if(0 == count($rowdata))
			{
				echo "<script>alert('" . translate('C_SELECT_AREA_TEXT') . "');</script>";
				echo " error id $id  can not find this data ";
				return;
			}
			if (0 == $data['isforever'])
			{
				if($data['starttime'] > $data['endtime'])
				{
					echo " starttime should be big than endtime";
					return;
				}
			}
			if (0 > $data['ration']) {
				echo " ration should be big than 0 ";
				return;
			}
			
			//修改当前数据库
			$result = $this->dyn_db->update('dynamic_treasurebox_ratio', $data, array('id'=>$id));
			
			if(false == $result)
			{
				echo " update data error";
				return;
			}
			
			//操作结果 是否正确
			$result = 0;

			$areanum = $_SESSION['area_selected_id'];
			//echo " areanum:$areanum ";
	
			//万不得已了，总不能传一个空数据让数据库报销了。。
			if($areanum == '')
			{
				echo "<script>alert('" . translate('C_SELECT_AREA_TEXT') . "');</script>";
				return;
			}
			
			$url = $this->areaList[$areanum]."action=51&messageid=100004&indexid=$id";
			
			$strResultStr = vpost($url);
			if ($strResultStr != '0' || $strResultStr === FALSE) {
					echo " fail ";
					$sql = "delete from dynamic_treasurebox_ratio where id = $indexid ";
					$this->db->execute($sql);
			}else
			{
					echo 'success';
			}
			return;
		}
			
		$sql = "SELECT * FROM dynamic_treasurebox_ratio WHERE id={$id}";
		$rowdata = $this->dyn_db->one($sql);

		if(0 == count($rowdata))
		{
			echo "<script>alert('" . translate('C_SELECT_AREA_TEXT') . "');</script>";
			return;
		}
		
		$this->view->assign('boxtype',$this->boxTypeList);	//宝箱类型
		$this->view->assign('numbertype',$this->numberTypeList);	//抽取类型
		$this->view->assign('professiontype',$this->professionList);	//职业类型
		$this->view->assign('playerlevel',$this->playerLevelList);	//等级范围
		$this->view->assign('materialtype',$this->materialTypeList);	//材料类型
		$this->view->assign('objecttype',$this->objectTypeList);	//物品类型
			
		//print_r($rowdata);
		$this->view->assign("row", $rowdata);
		$this->view->display("mall/treasureboxratio/edit");
		
	}

	function multi() {
		
		$type = $this->input->post("type");
		$ids = $this->input->post("ids");
		//$_SESSION['glql']='999999';exit();
		var_dump($type);
		var_dump($ids);
		$c = 0;
		$r = '';
		$allids = $ids = explode(',', $ids);
		if (count($ids) == 0)
		{
			$r = translate('C_INVALID_PARAMS');
		} else
		{
			$ids = "'" . implode("','", $ids) . "'";
			if ($type == 'delete')
			{
				//$strResult = vpost($this->config['host_url'] . 'type_id=' . $id . "action=36");
				//$c = (int) $strResult == 0 ? 1 : 0;
				insert_log(translate('MENU_MALL_TREASUREBOXRATIO'),translate('MULTI_DEL'),array('ids'=> implode(",", $allids)));
				$c = 1;
			} else
			{
				$r = translate('C_INVALID_PARAMS');
			}
		}
		json_output($c, $r);
		
	}

	//初始化枚举
	function initEnum()
	{
		$this->boxTypeList = array(
			'10001'=>'初级宝箱',
			'10002'=>'高级宝箱',
		);
		$this->numberTypeList = array(
			'1'=>'单次抽',
			'2'=>'十连抽',
			'0'=>'首次抽',
		);
		$this->materialTypeList = array(
			/*
			'1'=>'初级材料',
			'2'=>'中级材料',
			'3'=>'高级材料',
			'4'=>'幸运石',
			'5'=>'锻造卷',
			'6'=>'职业装备',
			'7'=>'通用装备',
			'8'=>'宠物',
			'9'=>'其它',
			*/
			'10'=>'装备',
			//'11'=>'材料',
			'12'=>'时装',
			'13'=>'消耗品',
			'14'=>'任务物品',
			'15'=>'称号背包',
			'16'=>'宠物背包',
			'17'=>'祝福背包',
		);
		$this->playerLevelList = array(
			'0'=>'0-6',
			'1'=>'7-16',
			'2'=>'17-26',	
			'3'=>'27-36',
			'4'=>'37-46',
			'5'=>'47-56',
			'6'=>'57-66',	
			'7'=>'67-76',
			'7'=>'77-86',
			'8'=>'87-96',
		);
		
		$tmpTypeList = get_type_object_detail(); //物品信息
		$equipList = get_equipment_list();	//装备信息
		
		foreach ($tmpTypeList as $id => $value)
		{
			//echo " id = $id ";
			//print_r($value);
			$this->objectTypeList[$value['kind']][$id]['id'] = $id;
			$this->objectTypeList[$value['kind']][$id]['name'] = $value['name'];
			$this->objectTypeList[$value['kind']][$id]['profession'] = -1;	//-1表示通用
			
			if(10 == $value['kind']) //装备才分职业
			{
				$this->objectTypeList[$value['kind']][$id]['profession'] = $equipList[$id]['profession'];
			}			
		}
		//print_r($this->objectTypeList);
	}

	function  getTotalRatio()
	{
		$this->dyn_db->select_db();
		//先把总概率统计下
		$sql = "SELECT box_id,choice_type,level_type,SUM(ration) AS totalration FROM dynamic_treasurebox_ratio GROUP BY box_id,choice_type, level_type";
		//echo "sql2 = $sql";
		$this->dyn_db->query($sql);
		$totalRatio = array();	//概率集合
		while ($n = $this->dyn_db->get_array('default'))
		{
			$box_id = $n['box_id'];
			$number_type = $n['choice_type'];
			$level_type = $n['level_type'];
			$t = $n['totalration'] == 0? 1:$n['totalration'];
			
			$this->totalRatio[$box_id][$number_type][$level_type] = $t;
		}
	}
	
	function  __destruct()
	{
		if($this->dyn_db != null)
		{
			$this->dyn_db->free_all();
		}
	}
}

?>
